<template>
  <view>
    <topBackGround :backisShow="1" :banner="1"></topBackGround>
    <div v-show=" state.index===0 ||  state.index===1 ||   state.index===2" class="title">第二步：绑定设备</div>
    <div v-show=" state.index===3" class="title">第三步：配对设备</div>
    <div v-show=" state.index===4" class="title">第四步：连接网络</div>
    <view class="container">

        <!-- 手机蓝牙已开启，下一步 -->
        <view v-show="state.index===0" class="bind_item">
            <text class="title_tips">请确保手机蓝牙已开启</text>
            <button @click="openBluetooth" type="button" class="main_btn">手机蓝牙已开启，下一步</button>
            <!-- <button @click="closeBluetooth" type="button" class="main_btn">结束流程</button> -->
            <button @click="wechatBluetoothAuthUtils" type="button" class="then_btn">手机蓝牙未开启</button>
        </view>
        <!-- 设备查找中 -->
        <view v-show="state.index===1" class="bind_item">
            <text class="title_black">设备查找中</text>
            <text class="title_tips2">正在搜寻设备请稍后</text>
            <view class="search_gif_con">
              <image class="search_gif" src="https://tc-nj-brush-od-pub-1324023246.cos.ap-nanjing.myqcloud.com/static/images/searchGif.gif" />
            </view>
        </view>
        <!-- 未查找到设备 -->
        <view v-show="state.index===2"  class="bind_item">
            <text class="title_error">未查找到设备</text>
            <text class="title_tips2">请打开手机蓝牙后重新绑定设备</text>
            <view class="no_device_con">
              <image class="no_device" src="../../images/no_device.png" />
            </view>
            <button @click="bindagain" type="button" class="main_btn">重新绑定设备</button>
        </view>

        <!-- 设备列表 -->
        <view v-show="state.index===3">
          <text class="title_tips">选择要配对的毛笔，点击去连接</text>
          <view class="pen_content">
              <penList 
                :penData="state.penListData" 
                @connect="connectPen" 
                ></penList>
              <!-- <text class="no_more"> - 没有更多了 -</text> -->
          </view>
        </view>

        <!-- wifi列表 -->
        <view v-show="state.index===4">
          <text class="title_tips">选择要配对的wifi, 点击去连接</text>
          <view class="pen_content">
              <wifiList 
                :wifiData="state.wifiList" 
                @connect="connectWifi" 
                ></wifiList>
              <!-- <text class="no_more"> - 没有更多了 -</text> -->
          </view>
        </view>
    </view>
  </view>
  </template>
    
  <script setup>
  import Taro from '@tarojs/taro';
  import penList from '../../components/penList.vue';
  import wifiList from '../../components/wifiList.vue';
  import topBackGround from '../../../src/components/backGround.vue'
  import { ref, reactive, onMounted, computed, watch } from 'vue'
  import { getCurrentInstance } from 'vue';
  import { useBluetoothStore } from '../../store/blueTooth'

  const { 
    state, 
    setFilterName, 
    openBluetoothAdapter, 
    resetState,
    startBluetoothDevicesDiscovery, 
    stopBluetoothDevicesDiscovery,
    closeBluetoothAdapter,
    writeBLECharacteristicValue,
    createBLEConnection,
    closeBLEConnection
  } = useBluetoothStore()

  

  // console.log( 'state.index::::', state.index )
  Taro.getLocation({
    type: 'gcj02',
    success(res) {
      console.log('getLocation:',res)
    }
  })

 
  const instance = getCurrentInstance();
  instance.appContext.config.globalProperties.$loadFontFace()

  let index = ref(0) // 0. 手机蓝牙已开启，下一步   1.设备查找中    2.未查找到设备

  // 查找蓝牙连接
  function openBluetooth() {
    resetState()
    setFilterName('Smartpen')
    console.log("调用了 setFilterName('Smartpen')")
    state.index = 1

    // closeBluetoothAdapter() // 每次开启前结束流程
    // openBluetoothAdapter()
    Taro.closeBluetoothAdapter({
      success (res) {
        openBluetoothAdapter()
      }
    })
  }

  function closeBluetooth() {
    closeBluetoothAdapter()
  }


  // 点击链接按钮
  function connectPen(item) {

    Taro.showLoading({
      title: '连接中'
    })

    console.log('连接中- item.deviceId:', item.deviceId)
   
    state.mac = item.deviceId
    state.name = item.nickName
    console.log('item.deviceId:', item.deviceId)
    console.log('item.nickName:', item.nickName)
    console.log( 'state.deviceId:', state.deviceId )
    console.log( 'state.nickName:', state.name )

    createBLEConnection(state.mac, state.name || state.localName)
   
    // 获取Wi-Fi列表
    // state.shouldAppend = false
    
    watch(()=>state.canWrite, (val) =>{
      if(val) {
        writeBLECharacteristicValue([0x04])
      }
    })

    watch(()=>state.isFinishWifiList,(value) => {
      console.log('wifi列表接受完毕-state.wifiList：', state.wifiList, value)
      if(value) {
        state.index = 4
        Taro.hideLoading()
      }
    })

    // Taro.navigateTo({
    //   url:'/pages/linkwifi/index',
    // })

    
    // createBLEConnection(item.deviceId, item.nickName || item.localName)
    // createBLEConnection(item.deviceId, item.name || item.localName)
  }

  // 点击链接Wifi
  function connectWifi(item) {
    state.chooseWifiName = item.ssid
    Taro.navigateTo({
      url:'/pages/linkwifi/index',
    })
  }

   // 重新连接
  function bindagain() {
    closeBluetoothAdapter() // 每次开启前结束流程 state.index
    state.index = 0
  }

  const bringBluetoothRight = () => {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.bluetooth']) {
            // 判断微信蓝牙是否授权
            resolve(wechatBluetoothAuthUtils());
          } else {
            Taro.authorize({
              scope: 'scope.bluetooth',
              success: () => {
                // 同意微信授权
                resolve(wechatBluetoothAuthUtils());
              },
              fail: () => {
                showModal({
                  content: 'xxxx想要开启蓝牙完成连接，请开启小程序蓝牙授权',
                  showCancel: false,
                  success: () => {
                    openSetting({
                      success: () => {
                        if(res.authSetting['scope.bluetooth']) {
                          // 同意微信授权
                          resolve(wechatBluetoothAuthUtils())
                        }
                      }
                    })
                  }
                })
              }
            })
          }
        }
      })
    })
  }
  
  // 未开启蓝牙按钮，点击进入系统蓝牙
  const wechatBluetoothAuthUtils = () => {
    const { bluetoothEnabled, platform } = wx.getSystemInfoSync();
    // 设备为IOS时， 微信蓝牙是否开启
    if(platform === 'ios') {
      return new Promise((resolve, reject) => {
        // 初始化蓝牙模块（用openBluetoothAdapter 方法解决部分ios设备，授权蓝牙失败的问题）
        wx.openBluetoothAdapter({
          success: () => {
            // 开启蓝牙功能=》 初始化拾果sdk
            resolve(true)
          },
          fail: (openBlueFail) => {
            if (openBlueFail.state === 3) {
              // 说明微信应用蓝牙未授权
              wx.showModal({
                content: '检测到您未允许微信访问蓝牙权限，是否打开系统设置？',
                showCancel: false,
                confirmText: '前往设置',
                success: () => {
                  // 跳转微信应用权限
                  wx.openAppAuthorizeSetting();
                }
              })
            } else if (openBlueFail.state === 4) {
              // 说明系统蓝牙未开启
              wx.showModal({
                content: '蓝牙设置 - 小程序需要通过蓝牙搜索和连接设备，请确认手机蓝牙功能是否开启？',
                showCancel: false,
                confirmText: '我已开启',
                success: async () => {
                  const { bluetoothEnabled, platform } = wx.getSystemInfoSync();
                  if (bluetoothEnabled) {
                    // 开启蓝牙功能
                    resolve(true)
                  } else {
                    Toast({title: '手机蓝牙未开启'})
                  }
                }
              })
            } else {
              return new Promise((resolve, reject) => {
                // andriod
                if (!bluetoothEnabled) {
                  // 说明系统蓝牙未开启
                  wx.showModal({
                    content: '蓝牙设置 - 小程序需要通过蓝牙搜索和连接设备，请确认手机蓝牙功能是否开启？',
                    showCancel: false,
                    confirmText: '我已开启',
                    success: async () => {
                      const { bluetoothEnabled, platform } = wx.getSystemInfoSync();
                      if (bluetoothEnabled) {
                        // 开启蓝牙功能
                        resolve(true);
                      } else {
                        Toast({title: '手机蓝牙未开启'})
                      }
                    }
                  })
                } else {
                  // 开启蓝牙功能
                  resolve( true )
                }
              })
            }
          }
        })
      })
    }
  }
  </script>
  
  <style>
  .search_gif_con, .no_device_con {
    width: 100%;
    height: 500px;
    text-align: center;
    margin-top: 60px;
  }
  .search_gif, .no_device {
    width: 240px;
    height: 276px;
  }

  .no_more{
    color: #C3B3A0;
    display: inline-block;
    width: 100%;
    text-align: center;
  }
  
  </style>